package com.shiguiwu.springmybatis.app.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Date;

/**
 * @description: mybaits
 * @author: stone
 * @date: Created by 2021/1/13 22:54
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.config
 */
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = {"com.shiguiwu.springmybatis.app.mapper","com.shiguiwu.springmybatis.app.repository.mapper"})
public class MybatisPlusConfig {




    @Bean
    public PaginationInterceptor interceptor() {

        return new PaginationInterceptor();
    }

    //属性填充的注册
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MyBatisPlusMetaObjectHandler();
    }


    // 注册乐观锁插件
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }


    @Slf4j
    public static class MyBatisPlusMetaObjectHandler implements MetaObjectHandler {

        @Override
        public void insertFill(MetaObject metaObject) {
            log.info("insert fill ........");
            this.setFieldValByName("createTime", new Date(), metaObject);
            this.setFieldValByName("updateTime", new Date(), metaObject);
        }

        @Override
        public void updateFill(MetaObject metaObject) {
            log.info("update fill..........");
            this.setFieldValByName("updateTime", new Date(), metaObject);

        }
    }





}
